//
//  B_ChangeDataVC.m
//  DreamOf
//
//  Created by 薛小刚 on 2018/8/19.
//  Copyright © 2018年 薛小刚. All rights reserved.
//

#import "B_ChangeDataVC.h"
#import "B_ChangeDataHeaderView.h"
#import "B_ChangeDataFooterView.h"
#import "B_ChangeDataTVC.h"
#import "XGPhotoManager.h"
#import "B_AddBankModel.h"
#import "XGDatePicker.h"
#import "AddressPickerView.h"
#import "B_UserBasicModel.h"

@interface B_ChangeDataVC ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate, UITextFieldDelegate>
@property (nonatomic, strong) BaseTableView * mainView;
/// 用户选择的图片
@property (nonatomic, strong) NSMutableArray * imageArray;

@property (nonatomic, strong) XGPhotoManager * photoManager;

@property (nonatomic, strong) UIImage * headerImage;

@property (nonatomic, strong) B_UserBasicModel * userModel;

@end

@implementation B_ChangeDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"个人资料"];
    self.view = self.mainView;
    WeakSelf(weSelf, self);
    
    [self setRightTextBarButtonItemWithFrame:CGRectZero title:@"保存" titleColor:[UIColor color_text_red] backImage:@"" selectBackImage:@"" action:^(GUIButton *button) {
        /// TODO:保存
        HXLog(@"保存按钮点击了");
        [weSelf.view endEditing:YES];
        [weSelf saveData];
    }];
    B_AddBankModel * model0 = [B_AddBankModel initB_AddBankModelWithTitle:@"昵称" placeholder:@"请输入昵称" mapword:@"昵称" alert:@"请输入昵称"];
    B_AddBankModel * model1 = [B_AddBankModel initB_AddBankModelWithTitle:@"签名" placeholder:@"请输入签名" mapword:@"签名" alert:@"请输入签名"];
    B_AddBankModel * model2 = [B_AddBankModel initB_AddBankModelWithTitle:@"性别" placeholder:@"请选择性别" mapword:@"性别" alert:@"请选择性别"];
    B_AddBankModel * model3 = [B_AddBankModel initB_AddBankModelWithTitle:@"生日" placeholder:@"请选择出生日期" mapword:@"生日" alert:@"请选择出生日期"];
    B_AddBankModel * model4 = [B_AddBankModel initB_AddBankModelWithTitle:@"城市" placeholder:@"请选择城市" mapword:@"城市" alert:@"请选择城市"];
    self.dataArray = [NSMutableArray arrayWithObjects:model0, model1, model2, model3, model4, nil];
    [self getData];
}

- (void)getData {
    WeakSelf(weSelf, self);
    [NetworkingManager getNetworkRequestWithUrlString:[NSString stringWithFormat:@"/yearnfor/inter/user/selectUserInfo/%@", getUserId()] parameters:nil isCache:YES succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20010"]) {
            NSLog(@"data is %@", data);
            weSelf.userModel = [B_UserBasicModel mj_objectWithKeyValues:data[@"values"]];
            for (B_AddBankModel * model in weSelf.dataArray) {
                if ([model.map_word isEqualToString:@"昵称"]) {
                    model.B_noneText0 = weSelf.userModel.nickName;
                } else if ([model.map_word isEqualToString:@"签名"]) {
                    model.B_noneText0 = weSelf.userModel.signature;
                } else if ([model.map_word isEqualToString:@"性别"]) {
                    model.B_noneText0 = [weSelf.userModel.sex isEqualToString:@"1"] ? @"男" : @"女";
                } else if ([model.map_word isEqualToString:@"生日"]) {
                    model.B_noneText0 = weSelf.userModel.age;
                } else if ([model.map_word isEqualToString:@"城市"]) {
                    model.B_noneText0 = [NSString stringWithFormat:@"%@ %@ %@", weSelf.userModel.province, weSelf.userModel.city, weSelf.userModel.district];
                }
            }
            [weSelf.mainView.tableView reloadData];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}



- (BaseTableView *)mainView {
    if (!_mainView) {
        WeakSelf(weSelf, self);
        _mainView = [[BaseTableView alloc] init];
        
        [_mainView setTableViewFrameWithTop:0 left:0 right:0 bottom:0];
        [_mainView.tableView registerNib:[UINib nibWithNibName:@"B_ChangeDataTVC" bundle:nil] forCellReuseIdentifier:@"B_ChangeDataTVC"];
        _mainView.numberOfSectionsBlock = ^NSInteger(UITableView *tableView) {
            return 2;
        };
        _mainView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                return 0;
            }
            return weSelf.dataArray.count;
        };
        
        _mainView.heightForHeaderBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                return 150;
            }
            return 10;
        };
        _mainView.viewForHeaderBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                B_ChangeDataHeaderView * header = [B_ChangeDataHeaderView initB_ChangeDataHeaderView];
                if (ISNULL(weSelf.headerImage)) {           /// 设置网络头像
                    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:weSelf.userModel.portrait] options:SDWebImageHighPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                        
                    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                        [header.B_userIconButton setBackgroundImage:image forState:UIControlStateNormal];
                    }];
                } else {
                    [header.B_userIconButton setBackgroundImage:weSelf.headerImage forState:UIControlStateNormal];
                }
                header.userIconAction = ^(UIButton *btn) {
                    //TODO:更换用户头像
                    [weSelf alertViewWithTitle:@"请选择" message:@"" buttonsTitles:@[@"相机", @"从相册选择", @"取消"] action:^(NSInteger index) {
                        if (index == 0) {
                            [weSelf.photoManager openCamereWithController:weSelf withImage:^(UIImage *image) {
                                weSelf.headerImage = image;
                                [btn setBackgroundImage:image forState:UIControlStateNormal];
                            }];
                        } else if (index == 1) {
                            [weSelf.photoManager openSinglePhotoWithController:weSelf withImage:^(UIImage *image) {
                                weSelf.headerImage = image;
                                [btn setBackgroundImage:image forState:UIControlStateNormal];
                            }];
                        }
                    }];
                };
                return header;
            }
            return nil;
        };
        
        _mainView.heightForRowBlock = ^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return 68;
        };
        _mainView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            if (indexPath.section == 0) {
                UITableViewCell * cell = [[UITableViewCell alloc] init];
                return cell;
            }
            B_ChangeDataTVC * cell = [tableView dequeueReusableCellWithIdentifier:@"B_ChangeDataTVC" forIndexPath:indexPath];
            cell.B_textfield.delegate = weSelf;
            cell.B_textfield.tag = indexPath.row;
            B_AddBankModel * model = weSelf.dataArray[indexPath.row];
            cell.B_keyLabel.text = model.key_title;
            cell.B_textfield.placeholder = model.placeholder_name;
            if (ISNULL(model.value_name)) {
                cell.B_textfield.text = model.B_noneText0;
            } else {
                cell.B_textfield.text = model.value_name;
            }
            if ([model.map_word isEqualToString:@"性别"] || [model.map_word isEqualToString:@"生日"] || [model.map_word isEqualToString:@"城市"]) {
                cell.B_textfield.userInteractionEnabled = NO;
            } else {
                cell.B_textfield.userInteractionEnabled = YES;
            }
            return cell;
        };
       
        _mainView.heightForFooterBlock = ^CGFloat(UITableView *tableView, NSInteger section) {
            
            if (section == 0) {
                CGFloat height = (SCREEN_WIDTH - 50) / 4.;
                if (weSelf.imageArray.count >= 8) {
                    return height * (weSelf.imageArray.count % 4 == 0 ? weSelf.imageArray.count / 4 : weSelf.imageArray.count / 4 + 1) + 30;
                } else {
                    return height * ((weSelf.imageArray.count + 1) % 4 == 0 ? (weSelf.imageArray.count + 1) / 4 : (weSelf.imageArray.count + 1) / 4 + 1) + 30;
                }
            }
            return 0.1f;
        };
        _mainView.viewForFooterBlock = ^UIView *(UITableView *tableView, NSInteger section) {
            if (section == 0) {
                B_ChangeDataFooterView * view = [B_ChangeDataFooterView initB_ChangeDataFooterView];
                view.imageArray = weSelf.imageArray;
                __block NSMutableArray * imageArray = [NSMutableArray array];
                view.deleteAction = ^(NSIndexPath *indexPath) {
//                    [imageArray removeObjectAtIndex:indexPath.row];
                    [weSelf.photoManager deleteImageWithIndex:indexPath.row];
                    [weSelf.imageArray removeObjectAtIndex:indexPath.row];
                    [tableView reloadData];
                };
                view.collectionTapAction = ^(NSIndexPath *indexPath) {
                    if (weSelf.imageArray.count == 8) {
                        //TODO:查看大图
                        
                        
                    } else {
                        if (weSelf.imageArray.count == indexPath.row) { // 选在照片
                            [weSelf alertViewWithTitle:@"请选择" message:@"" buttonsTitles:@[@"相机", @"从相册选择", @"取消"] action:^(NSInteger index) {
                                if (index == 0) {
                                    [weSelf.photoManager openCamereWithController:weSelf withImage:^(UIImage *image) {
                                        [weSelf.imageArray addObject:image];
                                        [tableView reloadData];
                                    }];
                                } else if (index == 1) {
                                    [weSelf.photoManager openMorePhotosWithController:weSelf maxNum:8 withImage:^(NSArray *imageArr, NSArray *array) {
                                        [weSelf.imageArray removeAllObjects];
                                        [weSelf.imageArray addObjectsFromArray:imageArr];
                                        [tableView reloadData];
                                        imageArray = [NSMutableArray arrayWithArray:array];
                                    }];;
                                }
                            }];
                        } else {
                            //TODO:查看大图
                            
                        }
                    }
                };
                return view;
            }
            return nil;
        };
        _mainView.didSelectRow = ^(UITableView *tableView, NSIndexPath *indexPath) {
            if (indexPath.section == 1) {
                B_AddBankModel * model = weSelf.dataArray[indexPath.row];
                if ([model.map_word isEqualToString:@"性别"]) {
                    [weSelf alertViewWithTitle:@"请选择" message:@"" buttonsTitles:@[@"男", @"女", @"取消"] action:^(NSInteger index) {
                        if (index == 0) {
                            model.value_name = @"男";
                        } else if (index == 1) {
                            model.value_name = @"女";
                        } else {
                            model.value_name = @"";
                        }
                        [weSelf.mainView.tableView reloadData];
                    }];
                } else if ([model.map_word isEqualToString:@"生日"]) {
                    XGDatePicker * date = [[XGDatePicker alloc] initWithType:PGDatePickerModeDate];
                    [date showWithController:weSelf Date:^(NSString *date) {
                        model.value_name = date;
                        [weSelf.mainView.tableView reloadData];
                    }];
                } else if ([model.map_word isEqualToString:@"城市"]) {
                    AddressPickerView * address = [[AddressPickerView alloc] initWithShowQu:YES];
                    [address show];
                    address.sureMessage = ^(NSString *provice, NSString *city, NSString *area) {
                        model.value_name = [NSString stringWithFormat:@"%@ %@ %@", provice, city, area];
                        [weSelf.mainView.tableView reloadData];
                    };
                    
                }
            }
            
            
        };
        
        
        
        
    }
    return _mainView;
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (XGPhotoManager *)photoManager {
    if (!_photoManager) {
        _photoManager = [[XGPhotoManager alloc] init];
    }
    return _photoManager;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 保存数据
 */
- (void) saveData {
    // 重新组装图片上传的
    NSMutableArray * imageArr = [NSMutableArray array];
    if (!ISNULL(self.headerImage)) {
        [imageArr addObject:self.headerImage];
    }
    if (!ISNULL(self.imageArray) && self.imageArray.count != 0) {
        [imageArr addObjectsFromArray:self.imageArray];
    }
    WeakSelf(weSelf, self);
    
    if (!ISNULL(imageArr)  && imageArr.count != 0) {
        [NetworkingManager UploadmoreTaskWithURL:[NSString stringWithFormat:@"%@/yearnfor/inter/user/userPictureAdd", ServiceIp] imagesArray:imageArr parameterOfimages:@"files" parametersDict:nil compressionRatio:0.8 succeedBlock:^(NSDictionary *dict) {
            if ([dict[@"code"] isEqualToString:@"20010"]) {
                [weSelf uploadUserMessage:dict[@"values"]];
            } else {
                [KeyWindow makeToast:dict[@"message"]];
            }
        } failedBlock:^(NSError *error) {
            [KeyWindow makeToast:@"服务器异常"];
        }];
    } else {
        [self uploadUserMessage:nil];
    }
    
    
}

- (void) textFieldDidEndEditing:(UITextField *)textField {
    B_AddBankModel * model = self.dataArray[textField.tag];
    model.value_name = textField.text;
}

- (void) uploadUserMessage:(NSArray *) array {
    
    
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
    for (B_AddBankModel * model in self.dataArray) {
        if (!ISNULL(model.value_name)) {                /// 判断数据不为空在进行上传
            if ([model.map_word isEqualToString:@"昵称"]) {
                [dictionary setObject:model.value_name forKey:@"nickName"];
            } else if ([model.map_word isEqualToString:@"签名"]) {
                [dictionary setObject:model.value_name forKey:@"signature"];
            } else if ([model.map_word isEqualToString:@"性别"]) {
                if ([model.value_name isEqualToString:@"男"]) {
                    [dictionary setObject:@"1" forKey:@"sex"];
                } else if ([model.value_name isEqualToString:@"女"]) {
                    [dictionary setObject:@"2" forKey:@"sex"];
                }
            } else if ([model.map_word isEqualToString:@"生日"]) {
                [dictionary setObject:model.value_name forKey:@"birthday"];
            } else if ([model.map_word isEqualToString:@"城市"]) {
                NSArray * arr = [model.value_name componentsSeparatedByString:@" "];
                [dictionary setObject:arr[0] forKey:@"province"];
                [dictionary setObject:arr[1] forKey:@"city"];
                [dictionary setObject:arr[2] forKey:@"district"];
            }
        } else {
            if ([model.map_word isEqualToString:@"昵称"]) {
                [dictionary setObject:@"" forKey:@"nickName"];
            } else if ([model.map_word isEqualToString:@"签名"]) {
                [dictionary setObject:@"" forKey:@"signature"];
            } else if ([model.map_word isEqualToString:@"性别"]) {
                [dictionary setObject:@"" forKey:@"sex"];
            } else if ([model.map_word isEqualToString:@"生日"]) {
                [dictionary setObject:@"" forKey:@"birthday"];
            } else if ([model.map_word isEqualToString:@"城市"]) {
                
                [dictionary setObject:@"" forKey:@"province"];
                [dictionary setObject:@"" forKey:@"city"];
                [dictionary setObject:@"" forKey:@"district"];
            }
        }
    }
    [dictionary setObject:getUserId() forKey:@"userId"];
    if (!ISNULL(self.headerImage)) {
        [dictionary setObject:array[0] forKey:@"portrait"];
        if (!ISNULL(self.imageArray)) {
            NSMutableArray * arr = [NSMutableArray arrayWithArray:array];
            [arr removeObjectAtIndex:0];
            [dictionary setObject:arr forKey:@"pictures"];
        } else {
            [dictionary setObject:@[] forKey:@"pictures"];
        }
    } else {
        [dictionary setObject:@"" forKey:@"portrait"];
        if (!ISNULL(self.imageArray)) {
            NSMutableArray * arr = [NSMutableArray arrayWithArray:array];
            [dictionary setObject:arr forKey:@"pictures"];
        } else {
            [dictionary setObject:@[] forKey:@"pictures"];
        }
    }
    WeakSelf(weSelf, self);
    NSLog(@"dic  %@", dictionary);
    [NetworkingManager postNetworkRequestWithUrlString:@"/yearnfor/inter/user/updateUserInfo" parameters:@{@"str": [dictionary mj_JSONString]} isCache:NO succeed:^(id data) {
        if ([data[@"code"] isEqualToString:@"20006"]) {
            [KeyWindow makeToast:@"资料修改成功"];
            [weSelf.navigationController popViewControllerAnimated:YES];
        } else {
            [KeyWindow makeToast:data[@"message"]];
        }
    } fail:^(NSError *error) {
        [KeyWindow makeToast:@"服务器异常"];
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
